<template>
 <ul class="list">
   <li class="item" v-for="item of letters" :key="item" :ref="item" @click="handleLetterClick"
   @touchstart.prevent="handleTouchStart"
   @touchmove="handleTouchMove"
   @touchend="handleTouchEnd"
   >{{item}}</li>
   <!-- <li class="item">A</li>
   <li class="item">A</li>
   <li class="item">A</li>
   <li class="item">A</li>
   <li class="item">A</li>
   <li class="item">A</li>
   <li class="item">A</li>
   <li class="item">A</li> -->
 </ul>
</template>

<script>
export default {
  name: 'cityAlphabet',
  props: {
    cities: Object
  },
  computed: { // 计算属性
    letters () { // 将cities里的数据转为数组
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false, // 标识位
      startY: 0,
      timer: null
    }
  },
  updated () { // 当页面数据更新的时候，同时页面完成自己的渲染后执行
    this.startY = this.$refs['A'][0].offsetTop // 获取A元素距离顶部具距离
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
      // console.log(e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) { // 通过函数截流setTimeout，减少touchmove执行频率
      // 右侧字母相应左侧滚动，确定字母位置通过，当前字母与A字母里
      // 顶部距离差除单个字母块高度
      if (this.touchStatus) { // touchStatus为true的时候再进行move
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          // console.log(startY)
          const touchY = e.touches[0].clientY - 79 // 当前手指的位置-顶部栏高度
          const index = Math.floor((touchY - this.startY) / 20) // 当前手指滑动的位置对应字母下标(20每个字母块高度)
          // console.log(index)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    display flex
    flex-direction column
    justify-content center
    position absolute
    top 1.58rem
    right 0
    bottom 0
    width .4rem
    .item
      line-height .4rem
      text-align center
      color $bgColor
</style>
